package jnpf.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.exception.DataException;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.service.UserService;
import jnpf.service.*;
import jnpf.entity.*;
import jnpf.util.*;
import jnpf.model.relationmange.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

import jnpf.annotation.JnpfField;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;
import jnpf.base.entity.ProvinceEntity;

import java.io.IOException;
import java.util.stream.Collectors;

import jnpf.engine.entity.FlowTaskEntity;
import jnpf.exception.WorkFlowException;
import org.springframework.transaction.annotation.Transactional;

/**
 * relationMange
 *
 * @版本： V3.5
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-04-11
 */
@Slf4j
@RestController
@Tag(name = "relationMange", description = "example")
@RequestMapping("/api/example/RelationMange")
public class RelationMangeController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private RelationMangeService relationMangeService;

    @Autowired
    private EntityService entityService;

    @Autowired
    private UserService userService;
    @Autowired
    private TagService tagService;


    /**
     * 列表
     *
     * @param relationMangePagination
     * @return
     */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody RelationMangePaginationDTO relationMangePagination) throws IOException {
        List<RelationMangeEntity> list = relationMangeService.getList(relationMangePagination.getRelationMangePaginationDTO());

        //通过分类id筛选列表
        String relationIdQuery = relationMangePagination.getRelationId();
        if (ObjectUtil.isNotEmpty(relationIdQuery)) {
            list = list.stream()
                    .filter(entity -> entity.getRelationId().equals(relationIdQuery))
                    .collect(Collectors.toList());
        }

        //查询列表中的实体id列表
        Set<String> entityIds = new HashSet<>();
        for (RelationMangeEntity entity : list) {
            if (entity.getEntityId() != null) {
                entityIds.add(entity.getEntityId());
            }
            if (entity.getTargetEntityId() != null) {
                entityIds.add(entity.getTargetEntityId());
            }
        }

        //通过实体id列表查询实体名称和责任人id
        Map<String, String> entityNameMap = new HashMap<>();
        Map<String, String> entityBelongUserIdMap = new HashMap<>();
        if (!entityIds.isEmpty()) {
            List<EntityEntity> entities = entityService.lambdaQuery().in(EntityEntity::getId, entityIds).list();
            for (EntityEntity entity : entities) {
                entityNameMap.put(entity.getId(), entity.getName());
                entityBelongUserIdMap.put(entity.getId(), entity.getBelongUserId());
            }
        }

        // 通过责任人id进行筛选
        String belongUserId = relationMangePagination.getBelongUserId();
        if (ObjectUtil.isNotEmpty(belongUserId)) {
            list = list.stream()
                    .filter(entity -> entityBelongUserIdMap.get(entity.getEntityId()).equals(belongUserId))
                    .collect(Collectors.toList());
        }

        // 通过实体名称进行筛选
        String entityName1 = relationMangePagination.getEntityName();
        if (ObjectUtil.isNotEmpty(entityName1)) {
            list = list.stream()
                    .filter(entity -> entityNameMap.get(entity.getEntityId()).equals(entityName1))
                    .collect(Collectors.toList());
        }

        // 查询责任人名称
        Set<String> belongUserIds = new HashSet<>(entityBelongUserIdMap.values());
        Map<String, String> belongUserNameMap = new HashMap<>();
        if (!belongUserIds.isEmpty()) {
            List<UserEntity> userEntities = userService.lambdaQuery().in(UserEntity::getId, belongUserIds).list();
            for (UserEntity userEntity : userEntities) {
                belongUserNameMap.put(userEntity.getId(), userEntity.getRealName());
            }
        }

        // 转换为 RelationMangePaginationVO 列表
        List<RelationMangePaginationVO> resultList = list.stream().map(entity -> {
            RelationMangePaginationVO vo = new RelationMangePaginationVO();
            vo.setId(entity.getId());
            vo.setEntityName(entityNameMap.get(entity.getEntityId()));
            vo.setBelongUserName(belongUserNameMap.get(entityBelongUserIdMap.get(entity.getEntityId())));
            vo.setDirection(entity.getDirection());
            vo.setEntityTargetName(entityNameMap.get(entity.getTargetEntityId()));
            return vo;
        }).collect(Collectors.toList());

        // 返回对象
        PageListVO vo = new PageListVO();
        vo.setList(resultList);
        PaginationVO page = JsonUtil.getJsonToBean(relationMangePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }

    /**
     * 创建
     *
     * @param relationMangeForm
     * @return
     */
    @PostMapping()
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid RelationMangeForm relationMangeForm) {
        String b = relationMangeService.checkForm(relationMangeForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b);
        }
        try {
            relationMangeService.saveOrUpdate(relationMangeForm, null, true);
        } catch (Exception e) {
            return ActionResult.fail("新增数据失败");
        }
        return ActionResult.success("创建成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody String ids) {
        List<String> idList = JsonUtil.getJsonToList(ids, String.class);
        int i = 0;
        for (String allId : idList) {
            this.delete(allId);
            i++;
        }
        if (i == 0) {
            return ActionResult.fail("删除失败");
        }
        return ActionResult.success("删除成功");
    }

    /**
     * 编辑
     *
     * @param id
     * @param relationMangeForm
     * @return
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid RelationMangeForm relationMangeForm, @RequestParam(value = "isImport", required = false) boolean isImport) {
        relationMangeForm.setId(id);
        if (!isImport) {
            String b = relationMangeService.checkForm(relationMangeForm, 1);
            if (StringUtil.isNotEmpty(b)) {
                return ActionResult.fail(b);
            }
        }
        RelationMangeEntity entity = relationMangeService.getInfo(id);
        if (entity != null) {
            try {
                relationMangeService.saveOrUpdate(relationMangeForm, id, false);
            } catch (Exception e) {
                return ActionResult.fail("修改数据失败");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        RelationMangeEntity entity = relationMangeService.getInfo(id);
        if (entity != null) {
            //主表数据删除
            relationMangeService.delete(entity);
        }
        return ActionResult.success("删除成功");
    }

    /**
     * 表单信息(详情页)
     * 详情页面使用-转换数据
     *
     * @param id
     * @return
     */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id) {
        RelationMangeEntity entity = relationMangeService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> relationMangeMap = JsonUtil.entityToMap(entity);
        relationMangeMap.put("id", relationMangeMap.get("id"));
        relationMangeMap = generaterSwapUtil.swapDataDetail(relationMangeMap, RelationMangeConstant.getFormData(), "680424951131414853", false);
        // 查询实体名称
        if (entity.getEntityId() != null) {
            EntityEntity entityEntity = entityService.getById(entity.getEntityId());
            if (entityEntity != null) {
                relationMangeMap.put("entityId", entityEntity.getName());
            }
        }

        if (entity.getTargetEntityId() != null) {
            EntityEntity targetEntity = entityService.getById(entity.getTargetEntityId());
            if (targetEntity != null) {
                relationMangeMap.put("targetEntityId", targetEntity.getName());
            }
        }

        // 查询标签名称
        if (entity.getTagId() != null) {
            // 假设存在一个 TagService 用于查询标签信息
            // 这里需要根据实际情况替换为你的标签查询逻辑
            TagEntity tagEntity = tagService.getById(entity.getTagId());
            if (tagEntity != null) {
                relationMangeMap.put("tagId", tagEntity.getName());
            }
        }
        return ActionResult.success(relationMangeMap);
    }

    /**
     * 获取详情(编辑页)
     * 编辑页面使用-不转换数据
     *
     * @param id
     * @return
     */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id) {
        RelationMangeEntity entity = relationMangeService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> relationMangeMap = JsonUtil.entityToMap(entity);
        relationMangeMap.put("id", relationMangeMap.get("id"));
        //副表数据
        //子表数据
        relationMangeMap = generaterSwapUtil.swapDataForm(relationMangeMap, RelationMangeConstant.getFormData(), RelationMangeConstant.TABLEFIELDKEY, RelationMangeConstant.TABLERENAMES);
        return ActionResult.success(relationMangeMap);
    }

}
